# from datetime import datetime # 原来用的注释掉
from django.utils import timezone as datetime # 不想大面积修改就这么做
from django.http import JsonResponse
from myadmin.models import Hosts, Cluster, Pod
from dao.get_nodes import get_nodes
from dao.get_pods import get_pods


def index(request):
    '''浏览主机信息'''
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    qs = Hosts.objects.filter(status__gt=0)  # 状态大于0
    list = []
    ok = 0
    not_ok = 0
    for host in qs:
        if host.status == 1:
            ok += 1
        else:
            not_ok += 1

        dir = host.toDict()
        pod_list = []
        try:
            pod_qs = Pod.objects.filter(hosts_ip=host.ip)
            for pod in pod_qs:
                pod_list.append(pod.toDict())
        except Exception as err:
            print(err)

        dir['pod_list'] = pod_list
        list.append(dir)
    return JsonResponse({'state': 1, 'msg': list, 'ok': ok, 'notOk': not_ok})



def insert(request):
    '''执行添加'''
    ip = request.POST.get('ip')
    if Hosts.objects.filter(ip=ip).exists():
        ob = Hosts.objects.get(ip=ip)
        if ob.status == 0:
            ob.status = 1

            ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.save()
            return JsonResponse({'state': 1, 'msg': '添加成功'})
        else:
            return JsonResponse({'state': 0, 'msg': 'ip已存在'})
    else:
        try:
            ob = Hosts()
            ob.ip = ip
            ob.name = request.POST.get('name')
            ob.status = 1
            ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.save()
            context = {'state': 1, 'msg': '添加成功'}
        except Exception as err:
            print(err)
            context = {'state': 0, "msg": "添加失败"}
        return JsonResponse(context)


def delete(request, uid):
    '''删除信息'''
    try:
        ob = Hosts.objects.get(id=uid)
        ob.status = 0
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'state': 1, "msg": "删除成功！"}
    except Exception as err:
        print(err)
        context = {'state': 0, "msg": "删除失败"}

    return JsonResponse(context)
    # return render(request, "myadmin/info.html", context)


def update(request, uid):
    '''执行编辑'''
    try:
        ob = Hosts.objects.get(id=uid)
        ob.name = request.POST.get('name')
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'state': 1, "msg": "修改成功！"}
    except Exception as err:
        print(err)
        context = {'state': 0, "msg": "修改失败"}
    return JsonResponse(context)


def refresh(request):
    get_nodes()  # 扫描主机
    get_pods()  #  扫描pod
    '''浏览主机信息'''
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    qs = Hosts.objects.filter(status__gt=0)  # 状态大于0
    list = []
    ok = 0
    not_ok = 0
    for host in qs:
        if host.status == 1:
            ok += 1
        else:
            not_ok += 1

        dir = host.toDict()
        pod_list = []
        try:
            pod_qs = Pod.objects.filter(hosts_ip=host.ip)
            for pod in pod_qs:
                pod_list.append(pod.toDict())
        except Exception as err:
            print(err)

        dir['pod_list'] = pod_list
        list.append(dir)

    return JsonResponse({'state': 1, 'msg': list, 'ok': ok, 'notOk': not_ok})